package com.lvmama.pangolin.timer.processor;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.MissProduct;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.entity.spider.TicketProduct;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.mt.service.TicketPdetailMtService;
import com.lvmama.pangolin.qnr.service.QNRTicketCommodityService;
import com.lvmama.pangolin.service.EarlyWarningService;
import com.lvmama.pangolin.service.MissProductService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.tc.service.TCTicketCommodityService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.tn.service.TNTicketCommodityService;
import com.lvmama.pangolin.util.SpringContextUtil;
import com.lvmama.pangolin.util.WeixinUtil;
import com.lvmama.pangolin.xc.service.XCTicketCommodityService;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckLastSpiderData   extends CommonJob
{
	@Autowired
	private  LMMCareProductService careProductService;
	@Autowired
	private  QNRTicketCommodityService qnrTicketService;
	@Autowired
	private  TCTicketCommodityService tcTicketService;
	@Autowired
	private  XCTicketCommodityService xcTicketService;
	@Autowired
	private  TNTicketCommodityService tnTicketService;
	@Autowired
	private TicketPdetailMtService ticketPdetailMtService;
	@Autowired
	private  MissProductService missProductService;

	@Autowired
	private TimerService timerService;

	@Autowired
	private EarlyWarningService earlyWarningService;

	private Logger logger = Logger.getLogger(CheckLastSpiderData.class);

	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		logger.info("开始检查数据...");
		String syscode=System.getProperties().getProperty("SYSCODE");
		if(timerService == null)
		{
			timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
		}
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("syscode", syscode);
		Date currentdate = new Date();
		Calendar ccal = Calendar.getInstance();
		ccal.setTime(currentdate);
		ccal.add(Calendar.DAY_OF_MONTH, -1);
		String cron = new SimpleDateFormat("dd MM ? yyyy").format(ccal.getTime());
		param.put("timer_cron", cron);
		List<String> statusList = new ArrayList<String>();
		statusList.add("5");
		param.put("timer_status", statusList);
		param.put("job_code", Constant.TICKE_BUS_TYPE);
		List<Timer> timerList =  timerService.queryTimerHListByCon(param);
		try
		{
			String content = checkSpider(timerList,Constant.TICKE_BUS_TYPE,ccal.getTime());
			if(StringTools.isValid(content))
			{
				WeixinUtil.sendWchat(parameter,content);
			}

		}
		catch (Exception e)
		{
			logger.error("检查数据失败", e);
		}
		logger.info("结束检查数据...");
	}

	public String checkSpider(List<Timer> timerList,String businessCode,Date date) throws Exception
	{
		logger.info("检查抓取情况开始...");
		StringBuffer warnContent = new StringBuffer();
		if(timerList != null && timerList.size() > 0)
		{
			if(careProductService == null)
			{
				careProductService = (LMMCareProductService) SpringContextUtil.getBean(LMMCareProductService.class);
			}
			List<LMMCareProduct> careList = careProductService.getAll(null,null,null,businessCode);
			Map<String,List<LMMCareProduct>> map = new HashMap<String,List<LMMCareProduct>>();
			if(careList != null && !careList.isEmpty())
			{
				List<LMMCareProduct> list = null;
				String cityCode = null;
				for (LMMCareProduct lmmCareProduct : careList)
				{
					cityCode = lmmCareProduct.getCityCode();
					list = map.get(cityCode);
					if(list == null )
					{
						list = new ArrayList<LMMCareProduct>();
						list.add(lmmCareProduct);
						map.put(cityCode, list);
					}
					else
					{
						list.add(lmmCareProduct);
					}
				}
			}
			String city = null;
			String taskId = null;
			String paramCode = null;
			Date taskDate = null;
			String companyCode = null;
			String busiCode = null;
			ConfigManager config = ConfigManager.getInstance();
			Map<String, Object> paramMap = new HashMap<String, Object>();
			List<TicketProduct> pist = null;
			List<MissProduct> tclist = new ArrayList<MissProduct>();
			int tcCount = 0;
			List<MissProduct> xclist = new ArrayList<MissProduct>();;
			int xcCount = 0;
			List<MissProduct> tnlist = new ArrayList<MissProduct>();;
			int tnCount = 0;
			List<MissProduct> qnrlist = new ArrayList<MissProduct>();;
			int qnrCount = 0;
			List<MissProduct> mtlist = new ArrayList<MissProduct>();;
			int mtCount = 0;
			for (Timer timer : timerList)
			{
				city = timer.getGranularity_value();
				taskId = timer.getTask_id();
				paramCode = timer.getTimer_param();
				taskDate = timer.getCreate_time();
				List<LMMCareProduct> cityCareList = map.get(city);
				companyCode = config.getParamValue(timer.getTimer_param(), "COMPANY_CODE");
				busiCode = config.getParamValue(timer.getTimer_param(), "BUSINESS_CODE",Constant.TICKE_BUS_TYPE);
				if(busiCode == null || !busiCode.equals(businessCode))
				{
					continue;
				}
				paramMap.put("task_id",taskId);
				paramMap.put("city_code",city);
				if("tc".equals(companyCode))
				{
					if(tcTicketService == null)
					{
						tcTicketService = (TCTicketCommodityService) SpringContextUtil.getBean(TCTicketCommodityService.class);
					}
					pist = tcTicketService.queryCommodityListByTaskID(paramMap);
					tclist.addAll(checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode));
					tcCount +=productCount(cityCareList,companyCode);
				}
				else if("xc".equals(companyCode))
				{
					if(xcTicketService == null)
					{
						xcTicketService = (XCTicketCommodityService) SpringContextUtil.getBean(XCTicketCommodityService.class);
					}
					pist = xcTicketService.queryCommodityListByTaskID(paramMap);
					xclist.addAll(checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode));
					xcCount +=productCount(cityCareList,companyCode);
				}
				else if("tn".equals(companyCode))
				{
					if(tnTicketService == null)
					{
						tnTicketService = (TNTicketCommodityService) SpringContextUtil.getBean(TNTicketCommodityService.class);
					}
					pist = tnTicketService.queryCommodityListByTaskID(paramMap);
					tnlist.addAll(checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode));
					tnCount +=productCount(cityCareList,companyCode);
				}
				else if("qnr".equals(companyCode))
				{
					if(qnrTicketService == null)
					{
						qnrTicketService = (QNRTicketCommodityService) SpringContextUtil.getBean(QNRTicketCommodityService.class);
					}
					pist = qnrTicketService.queryCommodityListByTaskID(paramMap);
					qnrlist.addAll(checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode));
					qnrCount +=productCount(cityCareList,companyCode);
				}
				else if("mt".equals(companyCode))
				{
					if(ticketPdetailMtService == null)
					{
						ticketPdetailMtService = (TicketPdetailMtService) SpringContextUtil.getBean(TicketPdetailMtService.class);
					}
					pist = ticketPdetailMtService.queryCommodityListByTaskID(paramMap);
					mtlist.addAll(checkMissProduct(cityCareList,companyCode,pist,taskId,taskDate,paramCode));
					mtCount +=productCount(cityCareList,companyCode);
				}


			}
			warnContent.append("门票  ").append(new SimpleDateFormat("yyyy-MM-dd").format(date)).append("  抓取率统计信息：").append("\n");
			warnContent.append("TC抓取信息:     ").append("\n")
					.append(content(tclist,tcCount)).append("\n");
			warnContent.append("XC抓取信息:   ").append("\n")
					.append(content(xclist,xcCount)).append("\n");
			warnContent.append("TN抓取信息:     ").append("\n")
					.append(content(tnlist,tnCount)).append("\n");
			warnContent.append("QNR抓取信息:     ").append("\n")
					.append(content(qnrlist,qnrCount));
			warnContent.append("MT抓取信息:     ").append("\n")
					.append(content(mtlist,mtCount));
		}

		logger.info("检查抓取情况结束...");
		return warnContent.toString();
	}

	private String content(List<MissProduct> missList,int count)
	{
		StringBuffer sb = new StringBuffer("");
		StringBuffer sbs = new StringBuffer("");
		int size = 0;
		if(missList != null && !missList.isEmpty())
		{
			size = missList.size();
			sbs.append(" 抓取失败产品:").append("\n");
			int i = 0;
			for (MissProduct missProduct : missList)
			{
				i ++;
				if(i > 10)
				{
					sbs.append("  ......").append("\n");
					break;
				}

				sbs.append("  "+missProduct.getProductName()).append("\n");
			}
		}
		sb.append(" 抓取总数：" + count).append("\n");
		sb.append(" 抓取成功：" + (count - size)).append("\n");
		sb.append(" 抓取失败：" + size).append("\n");
		sb.append(" 抓取成功率：" + StringTools.getPercent((count - size), count, "##.00%"))
				.append("\n").append(sbs.toString());
		return sb.toString();

	}
	private int productCount(List<LMMCareProduct> careList,String companyCode)
	{
		int count = 0;
		if(careList != null && !careList.isEmpty())
		{
			String url = null;
			for (LMMCareProduct careProduct : careList)
			{
				if("tc".equals(companyCode))
				{
					url = careProduct.getTc_url();

				}
				else if("xc".equals(companyCode))
				{
					url = careProduct.getXc_url();
				}
				else if("tn".equals(companyCode))
				{
					url = careProduct.getTn_url();
				}
				else if("qnr".equals(companyCode))
				{
					url = careProduct.getQnr_url();
				}else if ("mt".equals(companyCode)) {
					url = careProduct.getMt_url();
				}
				if(StringTools.isValid(url))
				{
					count ++;
				}

			}

		}

		return count;
	}
	private List<MissProduct> checkMissProduct(List<LMMCareProduct> careList,String companyCode,List<TicketProduct> spiderList
			,String taskId,Date taskDate,String paramCode)
	{
		List<MissProduct> list = new ArrayList<MissProduct>();

		if(careList != null && !careList.isEmpty())
		{
			String url = null;
			String name = null;
			String lvp = null;
			for (LMMCareProduct careProduct : careList)
			{
				lvp = careProduct.getProductId();
				if("tc".equals(companyCode))
				{
					url = careProduct.getTc_url();
					name = careProduct.getTc_name();

				}
				else if("xc".equals(companyCode))
				{
					url = careProduct.getXc_url();
					name = careProduct.getXc_name();
				}
				else if("tn".equals(companyCode))
				{
					url = careProduct.getTn_url();
					name = careProduct.getTn_name();
				}
				else if("qnr".equals(companyCode))
				{
					url = careProduct.getQnr_url();
					name = careProduct.getQnr_name();
				} else if ("mt".equals(companyCode)) {
					url = careProduct.getMt_url();
					name = careProduct.getMt_name();
				}
				boolean spiderFlag = false;
				if(!StringTools.isValid(url))
				{
					spiderFlag = true;
				}
				if(spiderList != null && !spiderList.isEmpty())
				{
					for (TicketProduct product : spiderList)
					{
						if(url != null && url.equalsIgnoreCase(product.getDetail_url()))
						{
							spiderFlag = true;
						}
						if(name != null && name.trim().equalsIgnoreCase(product.getScenery_name().trim()))
						{
							spiderFlag = true;
						}
						if(lvp != null && lvp.equalsIgnoreCase(product.getLv_product_id()))
						{
							spiderFlag = true;
						}

					}
				}
				if(!spiderFlag)
				{
					MissProduct missProduct = new MissProduct();
					missProduct.setBusinessCode(careProduct.getBusinessCode());
					missProduct.setCityCode(careProduct.getCityCode());
					missProduct.setCityName(careProduct.getCityName());
					missProduct.setCompanyCode(companyCode);
					missProduct.setDealFlag(0);
					missProduct.setProductId(lvp);
					missProduct.setProductName(careProduct.getProductName());
					missProduct.setName(name);
					missProduct.setUrl(url);
					Date date =  new Date();
					missProduct.setInsertTime(new Timestamp(date.getTime()));
					missProduct.setUpdateTime(new Timestamp(date.getTime()));
					missProduct.setTaskDate(taskDate);
					missProduct.setTaskId(taskId);
					missProduct.setParamCode(paramCode);
					list.add(missProduct);

				}
			}

		}

		return list;
	}


}
